package last.fm;

/***
 * @author Ragnvald Fuglestein
 */

import java.util.LinkedList;
import java.util.Queue;

public class LastFmJobWorker extends Thread {
	private static LastFmJobWorker instance = null;
	
	public static void jobCompleted(Runnable job) {
		instance.threads.remove(job);
	}
	
	public static void addJob(LastFmJob job) {
		if (instance == null) {
			instance = new LastFmJobWorker(job);
			instance.start();
		} else {
			instance.add(job);
		}
	}
	
	public static void madeRequest() {
		for(int i = 4; i > 0; i--) {
			instance.requesttime[i] = instance.requesttime[i - 1];
		}
		instance.requesttime[0] = System.currentTimeMillis();
	}
	
	private static void destroyInstance() {
		instance = null;
	}

	private Queue<LastFmJob> jobs = new LinkedList<>();
	private LinkedList<Runnable> threads = new LinkedList<>();
	
	long currenttime = System.currentTimeMillis();

	private long[] requesttime = new long[] { currenttime - 200l, currenttime - 200l, currenttime - 200l, currenttime - 200l, currenttime - 200l };

	private LastFmJobWorker(LastFmJob job) {
		super("LastFmJobWorker");
		add(job);
	}
	
	private void add(LastFmJob job) {
		jobs.add(job);
	}
	
	@Override public void run() {
		long sleep;
		while (jobs.size() > 0 || threads.size() > 0 || currenttime - requesttime[4] < 10000l) { // Keep thread alive 10 seconds after last thread finished
			currenttime = System.currentTimeMillis();
			int tsize = threads.size();
			long timetonext = requesttime[4] + 200l - currenttime;
			if (timetonext < 0) {
				if (jobs.size() > 0) {
					if (tsize < 1) { // TODO: Allow more threads ...
						Runnable r = jobs.remove();
						threads.add(r);
						new Thread(r).start();
						continue;
					} else sleep = 400;
				} else sleep = 200;
			} else {
				sleep = timetonext;
			}
			try {
				Thread.sleep(sleep);
			} catch (InterruptedException e) { }
		}
		destroyInstance();
	}
}
